package com.hb.trade.server.center.sys.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hb.core.pojo.center.sys.dto.ConsoleItemDTO;
import com.hb.core.pojo.center.sys.entity.ConsoleItemStatus;
import com.hb.core.pojo.center.sys.mapper.ConsoleItemMapper;
import com.hb.core.pojo.center.sys.entity.ConsoleItem;
import com.hb.trade.server.center.sys.service.ConsoleItemService;
import com.hb.trade.server.center.sys.service.ConsoleItemStatusService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * <p>
 * 操作台控制按钮信息表 服务实现类
 * </p>
 *
 * @author zhaojk
 * @since 2021-11-29
 */
@Service
public class ConsoleItemServiceImpl extends ServiceImpl<ConsoleItemMapper, ConsoleItem> implements ConsoleItemService {

    protected final ConsoleItemStatusService consoleItemStatusService;

    public ConsoleItemServiceImpl(ConsoleItemStatusService consoleItemStatusService) {
        this.consoleItemStatusService = consoleItemStatusService;
    }

    @Override
    public List<ConsoleItemDTO> itemChecked(Long statusId) {
        if (statusId == null) {
            return CollUtil.list(false);
        }
        return baseMapper.itemChecked(statusId);
    }

    @Override
    public boolean updateRelation(Long statusId, List<Long> itemIds) {
        baseMapper.removeByStatusId(statusId);
        List<ConsoleItemStatus> itemStatuses = CollUtil.list(false);
        for (Long itemId : itemIds) {
            ConsoleItemStatus itemStatus = new ConsoleItemStatus();
            itemStatus.setItemId(itemId);
            itemStatus.setStatusId(statusId);
            itemStatus.buildBaseData(1);
            itemStatuses.add(itemStatus);
        }
        return consoleItemStatusService.saveBatch(itemStatuses);
    }

    @Transactional
    @Override
    public boolean resort(Long parentId) {
        if (parentId == null) {
            return false;
        }
        // 查询当前数据下的所有子级数据
        QueryWrapper<ConsoleItem> query = Wrappers.query();
        query.eq("parent_id", parentId).orderByAsc("sort_code");
        List<ConsoleItem> list = list(query);

        // 重新设置排序号
        int index = 1;
        for (ConsoleItem projectConsoleItem : list) {
            projectConsoleItem.setSortCode(BigDecimal.valueOf(index));
            index++;
        }
        return updateBatchById(list);
    }

    @Override
    public BigDecimal maxSort(Long parentId) {
        BigDecimal maxSort = baseMapper.maxSort(parentId);
        if (maxSort == null) {
            return BigDecimal.ZERO;
        }
        return maxSort;
    }

}
